// handlepage.js
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';

export default {
    setup() {
        const route = useRoute();
        const disputeId = route.params.disputeId; // 获取纠纷ID
        const disputeDetails = ref(null); // 初始化纠纷详情
        const chatMessages = ref([]); // 初始化聊天记录
        const isProcessing = ref(false);

        // 获取纠纷详情
        const fetchDisputeDetails = async () => {
            try {
                const response = await fetch(`/disputes/detail?disputeId=${disputeId}`);
                const data = await response.json();
                if (data.code === 200 && data.data.dispute) {
                    disputeDetails.value = data.data.dispute;
                } else {
                    alert('加载纠纷详情失败');
                }
            } catch (error) {
                alert('获取纠纷详情时出错');
            }
        };

        // 获取历史聊天记录
        const fetchChatHistory = async (pageNum = 1, pageSize = 10) => {
            try {
                const response = await fetch(`/disputes/${disputeId}/history?pageNum=${pageNum}&pageSize=${pageSize}`);
                const data = await response.json();
                if (data.code === 200) {
                    chatMessages.value = data.data.disputeMessages || [];
                } else {
                    ElMessage.error('加载聊天记录失败');
                }
            } catch (error) {
                ElMessage.error('获取聊天记录时出错');
            }
        };

        // 裁定纠纷结果
        const handleDisputeResult = async () => {
            try {
                isProcessing.value = true;
                const response = await fetch(`/disputes/rule?disputeId=${disputeId}`);
                const data = await response.json();
                if (data.code === 0) {
                    ElMessage.success('裁定结果已处理');
                    fetchDisputeDetails();  // 重新加载纠纷详情
                } else {
                    ElMessage.error('裁定失败');
                }
            } catch (error) {
                ElMessage.error('裁定结果处理失败');
            } finally {
                isProcessing.value = false;
            }
        };

        // 页面加载时获取数据
        onMounted(() => {
            fetchDisputeDetails();
            fetchChatHistory();
        });

        return {
            disputeDetails,
            chatMessages,
            handleDisputeResult,
            isProcessing,
        };
    },
};
